package com.hard;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lxk on 2019/2/23.
 */
public class LRUCache146 {

    Map<Integer,Integer> map = null;

    Map<Integer,Integer> lruMap = null;

    Integer capacity = 0;

    Integer count = null;

    volatile Integer serial = null;

    public LRUCache146(int capacity) {
        this.map = new HashMap<>();
        this.lruMap = new HashMap<>();
        this.capacity = capacity;
        this.count = 0;
        this.serial = 0;
    }

    public int get(int key) {
        Integer res = map.get(key);
        if(res != null){
            lruMap.put(key,++this.serial);
        }
        return res == null ? -1 : res;
    }

    public void put(int key, int value) {
        //进行旧数据替换
        if(this.count>=this.capacity){
            if(map.keySet().contains(key)){
                map.put(key,value);
                lruMap.put(key,++this.serial);
                return ;
            }
            Integer minKey = null;
            Integer minValue = Integer.MAX_VALUE;
            for(Map.Entry<Integer,Integer> entry : lruMap.entrySet()){
                if(entry.getValue()<minValue){
                    minValue = entry.getValue();
                    minKey = entry.getKey();
                }
            }
            map.remove(minKey);
            lruMap.remove(minKey);
            map.put(key,value);
            lruMap.put(key,++this.serial);
        }else{
            map.put(key,value);
            lruMap.put(key,++this.serial);
            this.count++;
        }
    }

    public static void main(String[] args){
        LRUCache146 cache = new LRUCache146(2);
        System.out.println(cache.get(2));
        cache.put(2,6);
        System.out.println(cache.get(1));
        cache.put(1,5);
        cache.put(1,2);
        System.out.println(cache.get(1));
        System.out.println(cache.get(2));

        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        for(Map.Entry<Integer,Integer> entry : cache.map.entrySet()){
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        for(Map.Entry<Integer,Integer> entry : cache.lruMap.entrySet()){
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

    }

}
